package com.tuyrt.firstcode.kotlin.coroutine

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.RuntimeException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * Created by tuyrt7 on 2021/4/12.
 */

suspend fun <T> Call<T>.await(): T {
    return suspendCoroutine { continuation ->
        enqueue(object :Callback<T>{
            override fun onResponse(call: Call<T>, response: Response<T>) {
                response.body()?.let { continuation.resume(it) }
                    ?:continuation.resumeWithException(RuntimeException("response body is null"))
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                continuation.resumeWithException(t)
            }
        })
    }
}